<template>
	<view class="container">
		<!-- 顶部操作栏 -->
		<view class="header">
			<view class="cancel-btn" @tap="goBack">取消</view>
			<view class="publish-btn" @tap="handleUpload" :class="{ disabled: isUploading }">上传</view>
		</view>
		
		<!-- 媒体类型选择 -->
		<view class="media-type">
			<view 
				class="type-item" 
				:class="{ active: currentType === type.value }"
				v-for="type in mediaTypes" 
				:key="type.value"
				@tap="selectType(type.value)"
			>
				<text>{{ type.label }}</text>
			</view>
		</view>
		
		<!-- 媒体预览区域 -->
		<scroll-view 
			class="media-list" 
			scroll-y="true"
			:style="{ height: 'calc(100vh - 200rpx)' }"  
		>
			<!-- 图片上传区域 -->
			<view class="image-upload" v-if="currentType === 1">
				<!-- 图片预览列表 -->
				<view class="image-list" v-if="imageList.length > 0">
					<view class="image-item" v-for="(image, index) in imageList" :key="index">
						<image :src="image" mode="aspectFill" class="preview-image"></image>
						<view class="delete-btn" @tap="removeImage(index)">
							<uni-icons type="trash" size="20" color="#fff"></uni-icons>
						</view>
					</view>
				</view>
				
				<!-- 添加按钮 -->
				<view class="upload-box" @tap="chooseImages">
					<uni-icons type="image" size="40" color="#999"></uni-icons>
					<text class="tip">上传图片</text>
				</view>
			</view>
			
			<!-- 视频/音频上传区域 -->
			<view class="media-upload" v-else>
				<view class="upload-box" @tap="chooseMedia" v-if="!mediaUrl">
					<uni-icons :type="uploadIcon" size="40" color="#999"></uni-icons>
					<text class="tip">{{ uploadTip }}</text>
				</view>
				
				<!-- 媒体预览 -->
				<view class="preview-box" v-else>
					<!-- 图片预览 -->
					<image 
						v-if="currentType === 1"
						:src="mediaUrl" 
						mode="aspectFit"
						class="preview-image"
					></image>
					
					<!-- 视频预览 -->
					<video 
						v-else-if="currentType === 2"
						:src="mediaUrl"
						class="preview-video"
						:controls="false"
						:loop="true"
						:muted="true"
						:autoplay="true"
						object-fit="contain"
					></video>
					
					<!-- 音频预览 -->
					<view v-else-if="currentType === 3" class="preview-audio">
						<uni-icons type="sound" size="40" color="#999"></uni-icons>
						<text class="audio-name">已选择音频文件</text>
					</view>
					
					<!-- 删除按钮 -->
					<view class="delete-btn" @tap="removeMedia">
						<uni-icons type="trash" size="20" color="#fff"></uni-icons>
					</view>
				</view>
			</view>
			
			<!-- 底部占位,防止内容被遮挡 -->
			<view style="height: 40rpx;"></view>
		</scroll-view>
		
		<!-- 上传进度提示 -->
		<view class="upload-loading" v-if="isUploading">
			<view class="loading-content">
				<uni-icons type="spinner-cycle" size="30" color="#ff6b6b"></uni-icons>
				<text class="loading-text">{{ loadingText }}</text>
				<text class="progress-text" v-if="currentType === 1">{{ uploadProgress }}</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { api } from '@/utils/request'
import {onLoad} from "@dcloudio/uni-app"
// 媒体类型列表
const mediaTypes = [
	{ label: '图片', value: 1 },
	{ label: '视频', value: 2 },
	{ label: '音频', value: 3 }
]

// 当前选中的类型
const currentType = ref(1)
// 媒体文件地址
const mediaUrl = ref('')
// 是否正在上传
const isUploading = ref(false)
// 帖子ID
const postId = ref('')

// 图片列表
const imageList = ref([])

// 上传进度提示
const loadingText = ref('正在上传...')
const uploadProgress = ref('')

// 计算上传图标
const uploadIcon = computed(() => {
	switch(currentType.value) {
		case 1: return 'image'
		case 2: return 'videocam'
		case 3: return 'sound'
		default: return 'image'
	}
})

// 计算上传提示文字
const uploadTip = computed(() => {
	switch(currentType.value) {
		case 1: return '上传图片'
		case 2: return '上传视频'
		case 3: return '上传音频'
		default: return '上传文件'
	}
})

// 选择媒体类型
const selectType = (type) => {
	if(mediaUrl.value) {
		uni.showModal({
			title: '提示',
			content: '切换类型将清除已选择的文件，是否继续？',
			success: (res) => {
				if(res.confirm) {
					currentType.value = type
					mediaUrl.value = ''
				}
			}
		})
	} else {
		currentType.value = type
	}
}

// 检查必要参数
const checkParams = () => {
	if(!postId.value) {
		uni.showToast({
			title: '参数错误',
			icon: 'none'
		})
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
		return false
	}
	return true
}

// 选择图片
const chooseImages = async () => {
	if(!checkParams()) return
	
	try {
		const res = await uni.chooseImage({
			count: 9 - imageList.value.length, // 最多9张
			sizeType: ['compressed'],
			sourceType: ['album', 'camera']
		})
		
		if(res.tempFilePaths) {
			imageList.value.push(...res.tempFilePaths)
		}
	} catch(err) {
		console.error('选择图片失败', err)
	}
}

// 移除图片
const removeImage = (index) => {
	imageList.value.splice(index, 1)
}

// 选择媒体文件
const chooseMedia = async () => {
	if(!checkParams()) return
	
	try {
		let res
		switch(currentType.value) {
			case 1:  // 图片
				res = await uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera']
				})
				break
			case 2:  // 视频
				res = await uni.chooseVideo({
					compressed: true,
					sourceType: ['album', 'camera']
				})
				mediaUrl.value = res.tempFilePath
				return
			case 3:  // 音频
				// #ifdef APP-PLUS || MP
				res = await uni.chooseFile({
					count: 1,
					type: 'audio',
					extension: ['.mp3','.wav','.aac']
				})
				// #endif
				break
		}
		
		if(res.tempFilePaths) {
			mediaUrl.value = res.tempFilePaths[0]
		}
	} catch(err) {
		console.error('选择文件失败', err)
	}
}

// 移除媒体
const removeMedia = () => {
	mediaUrl.value = ''
}

// 处理上传
const handleUpload = async () => {
	if(!checkParams()) return
	
	// 图片批量上传
	if(currentType.value === 1) {
		if(imageList.value.length === 0) {
			uni.showToast({
				title: '请选择图片',
				icon: 'none'
			})
			return
		}
		
		if(isUploading.value) return
		isUploading.value = true
		
		try {
			// 批量上传图片
			const total = imageList.value.length
			for(let i = 0; i < imageList.value.length; i++) {
				loadingText.value = '正在上传图片...'
				uploadProgress.value = `(${i + 1}/${total})`
				await uploadMedia(imageList.value[i])
			}
			
			loadingText.value = '上传完成'
			uni.showToast({
				title: '上传成功',
				icon: 'success'
			})
			
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
			
		} catch(err) {
			console.error('上传失败', err)
			uni.showToast({
				title: err.message || '上传失败',
				icon: 'none'
			})
		} finally {
			isUploading.value = false
		}
		return
	}
	
	// 视频/音频上传
	if(!mediaUrl.value) {
		uni.showToast({
			title: '请选择文件',
			icon: 'none'
		})
		return
	}
	
	if(isUploading.value) return
	isUploading.value = true
	
	try {
		loadingText.value = currentType.value === 2 ? '正在上传视频...' : '正在上传音频...'
		await uploadMedia(mediaUrl.value)
		
		loadingText.value = '上传完成'
		uni.showToast({
			title: '上传成功',
			icon: 'success'
		})
		
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
		
	} catch(err) {
		console.error('上传失败', err)
		uni.showToast({
			title: err.message || '上传失败',
			icon: 'none'
		})
	} finally {
		isUploading.value = false
	}
}

// 上传单个媒体文件
const uploadMedia = (filePath) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: api.BASE_URL + '/api/post/create_post_media/',
			filePath: filePath,
			name: 'media_url',
			formData: {
				post_id: postId.value,
				media_type: currentType.value
			},
			success: (uploadRes) => {
				const data = JSON.parse(uploadRes.data)
				if(data.code === 200) {
					resolve(data)
				} else {
					reject(new Error(data.message))
				}
			},
			fail: reject
		})
	})
}

// 获取页面参数
onLoad((options) => {
	// 检查是否有post_id参数
	if(options.post_id) {
		postId.value = options.post_id
	} else {
		uni.showToast({
			title: '参数错误',
			icon: 'none'
		})
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	}
})

// 添加返回方法
const goBack = () => {
	// 如果正在上传，提示用户
	if(isUploading.value) {
		uni.showModal({
			title: '提示',
			content: '正在上传中，确定要返回吗？',
			success: (res) => {
				if(res.confirm) {
					uni.navigateBack()
				}
			}
		})
		return
	}
	
	// 如果有选择的媒体但未上传，提示用户
	if(imageList.value.length > 0) {
		uni.showModal({
			title: '提示',
			content: '有未上传的媒体，确定要返回吗？',
			success: (res) => {
				if(res.confirm) {
					uni.navigateBack()
				}
			}
		})
		return
	}
	
	// 直接返回
	uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background: #fff;
	display: flex;
	flex-direction: column;
	height: 100vh;
	overflow: hidden;
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #eee;
	height: 100rpx;
	box-sizing: border-box;
	
	.cancel-btn {
		font-size: 28rpx;
		color: #999;
		
		&:active {
			opacity: 0.7;
		}
	}
	
	.publish-btn {
		background: #ff6b6b;
		color: #fff;
		font-size: 28rpx;
		padding: 12rpx 30rpx;
		border-radius: 30rpx;
		
		&:active {
			opacity: 0.8;
		}
		
		&.disabled {
			opacity: 0.5;
			pointer-events: none;
		}
	}
}

.media-type {
	display: flex;
	padding: 20rpx;
	border-bottom: 1rpx solid #eee;
	height: 100rpx;
	box-sizing: border-box;
	
	.type-item {
		flex: 1;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #666;
		position: relative;
		
		&.active {
			color: #ff6b6b;
			font-weight: bold;
			
			&::after {
				content: '';
				position: absolute;
				bottom: -20rpx;
				left: 50%;
				transform: translateX(-50%);
				width: 40rpx;
				height: 4rpx;
				background: #ff6b6b;
				border-radius: 2rpx;
			}
		}
		
		&:active {
			opacity: 0.7;
		}
	}
}

.media-list {
	box-sizing: border-box;
	overflow-x: hidden;
	
	.image-upload {
		.image-list {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20rpx;
			margin-bottom: 20rpx;
			
			.image-item {
				position: relative;
				width: 100%;
				padding-bottom: 100%;
				border-radius: 12rpx;
				overflow: hidden;
				background: #f5f5f5;
				
				.preview-image {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					object-fit: cover;
				}
				
				.delete-btn {
					position: absolute;
					top: 10rpx;
					right: 10rpx;
					width: 40rpx;
					height: 40rpx;
					background: rgba(0, 0, 0, 0.5);
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					
					&:active {
						opacity: 0.7;
					}
				}
			}
		}
		
		.upload-box {
			width: 100%;
			padding-bottom: 100%;
			position: relative;
			
			&::before {
				content: '';
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background: #f5f5f5;
				border-radius: 12rpx;
			}
			
			.uni-icons,
			.tip {
				position: absolute;
				left: 50%;
				transform: translateX(-50%);
			}
			
			.uni-icons {
				top: 40%;
			}
			
			.tip {
				bottom: 30%;
				font-size: 28rpx;
				color: #999;
			}
			
			&:active {
				opacity: 0.7;
			}
		}
	}
	
	.media-upload {
		.upload-box {
			width: 100%;
			height: 600rpx;
			background: #f5f5f5;
			border-radius: 12rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			
			.tip {
				font-size: 28rpx;
				color: #999;
				margin-top: 20rpx;
			}
			
			&:active {
				opacity: 0.7;
			}
		}
		
		.preview-box {
			position: relative;
			width: 100%;
			height: 600rpx;
			border-radius: 12rpx;
			overflow: hidden;
			background: #000;
			
			.preview-image,
			.preview-video {
				width: 100%;
				height: 100%;
				object-fit: contain;
			}
			
			.preview-audio {
				width: 100%;
				height: 100%;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				background: #f5f5f5;
				
				.audio-name {
					font-size: 28rpx;
					color: #666;
					margin-top: 20rpx;
				}
			}
			
			.delete-btn {
				position: absolute;
				top: 20rpx;
				right: 20rpx;
				width: 60rpx;
				height: 60rpx;
				background: rgba(0, 0, 0, 0.5);
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				
				&:active {
					opacity: 0.7;
				}
			}
		}
	}
}

.upload-loading {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.6);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 999;
	
	.loading-content {
		background: #fff;
		border-radius: 12rpx;
		padding: 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		
		.uni-icons {
			animation: rotate 1s linear infinite;
		}
		
		.loading-text {
			font-size: 28rpx;
			color: #333;
			margin-top: 20rpx;
		}
		
		.progress-text {
			font-size: 24rpx;
			color: #999;
			margin-top: 10rpx;
		}
	}
}

@keyframes rotate {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}
</style>
